<?php

namespace app\admin\controller\template;

use app\common\controller\Backend;

/**
 * 佣金配置
 *
 * @icon fa fa-circle-o
 */
class CommissionConfig extends Backend
{

    /**
     * CommissionConfig模型对象
     * @var \app\admin\model\template\CommissionConfig
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\template\CommissionConfig;
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                if ($params['value'] > 100 || $params['value'] < 0) {
                    $this->error('佣金比例不能大于100%或者小于0%');
                }

                if ($this->model->where('title',$params['title'])->value('id')) {
                    $this->error('该配置已存在');
                }

                if ($this->model->where('key',$params['key'])->value('id')) {
                    $this->error('该配置 key 已存在');
                }

                $otherConfig = $this->model->sum('value');
                if (($otherConfig * 100 + $params['value']) > 100) {
                    $this->error('佣金比例不能大于100%');
                }
                $this->model->create($params);
                $this->success('请求成功');
            }
            $this->error();
        }

        return $this->view->fetch();
    }


    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                if ($params['value'] > 100 || $params['value'] < 0) {
                    $this->error('佣金比例不能大于100%或者小于0%');
                }

                $otherConfig = $this->model->where('id', '<>', $ids)->sum('value');
                if (($otherConfig * 100 + $params['value']) > 100) {
                    $this->error('佣金比例不能大于100%');
                }
                $row->value = $params['value'];
                try {
                    $row->save();
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }

                $this->success('请求成功');
            }
            $this->error();
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
